import {useState} from 'react';
import {useNavigate} from 'react-router-dom';

// 员工找回密码

interface UseFindPassword {
    findPassword: (id: string, name: string, phoneNumber: string, password: string) => Promise<void>;
    isLoading: boolean;
    error: string | null;
}

export function useFindPassword(): UseFindPassword {
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);

    const navigate = useNavigate();

    const findPassword = async (id: string, name: string, phoneNumber: string, password: string): Promise<void> => {
        setIsLoading(true);
        setError(null);
        try {
            const response = await fetch('http://localhost:6868/employee/forgetPassword', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({id, name, phone_number: phoneNumber, password}),
            });

            if (!response.ok) {
                throw new Error('找回密码失败');
            }

            // 注册成功，跳转到登录页面
            navigate('/');

        } catch (error) {
            setError((error as Error).message);
        } finally {
            setIsLoading(false);
        }
    };

    return {findPassword, isLoading, error};
}
